import { applyMiddleware, legacy_createStore as createStore } from 'redux'

import { get, getJson, remove, set, setJson } from '@/utils/storage'

import logger from './logger'

export interface GlobalState {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  userInfo?: { [propName: string]: any }
  token?: string | number
  networkStatus: boolean
  dashboardNum: number
  orgName?: string
  networks: number
}

const initialState: GlobalState = {
  userInfo: getJson('userInfo'),
  token: get('did'),
  networkStatus: true,
  dashboardNum: 0,
  orgName: get('orgName'),
  networks: 0,
}

function rootReducer(state = initialState, action) {
  switch (action.type) {
    case 'add-networks': {
      const networks = state.networks + 1
      console.log('networks', networks)
      return {
        ...state,
        networks,
      }
    }
    case 'sub-networks': {
      const networks = state.networks - 1
      console.log('networks', networks)
      return {
        ...state,
        networks,
      }
    }
    case 'update-settings': {
      const { settings } = action.payload
      return {
        ...state,
        settings,
      }
    }
    case 'update-userInfo': {
      const { userInfo = initialState.userInfo, userLoading } = action.payload
      setJson('userInfo', userInfo)
      return {
        ...state,
        userLoading,
        userInfo,
      }
    }
    case 'update-orgName': {
      const { orgName } = action.payload
      set('orgName', orgName)
      return { ...state, orgName: orgName }
    }
    case 'update-token': {
      const { token } = action.payload
      set('did', token)
      return { ...state, token: token }
    }
    case 'update-networkStatus': {
      const { networkStatus } = action.payload
      set('networkStatus', networkStatus)
      return { ...state, networkStatus: networkStatus }
    }

    case 'reset': {
      remove('did')
      remove('userInfo')
      return { ...state, token: '', userInfo: {} }
    }
    case 'update-dashboardNum': {
      const { dashboardNum } = action.payload
      return {
        ...state,
        dashboardNum,
      }
    }
    default:
      return state
  }
}

const store = createStore(rootReducer, applyMiddleware(logger))

export default store
